package com.lwl.concurrency.collection;

import java.util.concurrent.ConcurrentLinkedDeque;

import org.junit.Test;

/**
 * <b>Java 7引进实现了非阻塞线程安全并发列表的ConcurrentLinkedDeque类</b>
 * <pre>
 * 非阻塞列表，使用ConcurrentLinkedDeque类。
 * 阻塞列表，使用LinkedBlockingDeque类。
 * 用在生产者与消费者数据的阻塞列表，使用LinkedTransferQueue类。
 * 使用优先级排序元素的阻塞列表，使用PriorityBlockingQueue类。
 * 存储延迟元素的阻塞列表，使用DelayQueue类。
 * 非阻塞可导航的map，使用ConcurrentSkipListMap类。
 * 随机数，使用ThreadLocalRandom类
 * 原子变量，使用AtomicLong和AtomicIntegerArray类
 * </pre>
 * 
 * Created by liwenlong on 2018/1/16 17:46<br>
 */
public class ConcurrentLinkedDequeTest {

	public static class AddTask implements Runnable {
		private ConcurrentLinkedDeque<String> list;

		public AddTask(ConcurrentLinkedDeque<String> list) {
			this.list = list;
		}

		@Override
		public void run() {
			String name = Thread.currentThread().getName();
			for (int i = 0; i < 10000; i++) {
				list.add(name + " Element-" + i);
			}
			System.out.println("add...");
		}
	}

	public static class PollTask implements Runnable {

		private ConcurrentLinkedDeque<String> deque;

		public PollTask(ConcurrentLinkedDeque<String> deque) {
			this.deque = deque;
		}

		@Override
		public void run() {
			for (int i = 0; i < 5000; i++) {
				deque.pollFirst();
				deque.pollLast();
			}
			System.out.println("poll...");
		}

	}

	@Test
	public void test1() throws InterruptedException {
		ConcurrentLinkedDeque<String> deque = new ConcurrentLinkedDeque<>();
		AddTask task = new AddTask(deque);
		Thread[] threads = new Thread[100];
		for (int i = 0; i < threads.length; i++) {
			threads[i] = new Thread(task);
			threads[i].start();
		}
		System.out.printf("Main: %d AddTask threads have been launched\n", threads.length);

		for (Thread thread : threads) {
			thread.join();
		}
		System.out.printf("Main: Size of the List: %d\n", deque.size());
		PollTask pollTask = new PollTask(deque);
		for (int i = 0; i < threads.length; i++) {
			threads[i] = new Thread(pollTask);
			threads[i].start();
		}
		System.out.printf("Main: %d PollTask threads have been launched\n", threads.length);

		for (int i = 0; i < threads.length; i++) {
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.printf("Main: Size of the List: %d\n", deque.size());
		//不删除元素,如果列表为空，这些方法将抛出NoSuchElementExcpetion异常
		deque.getLast();
		deque.getFirst();
		//不删除元素,如果列表为空，这些方法将返回null值
		deque.peek();
		deque.peekFirst();
		deque.peekLast();
		//删除元素,如果列表为空，这些方法将抛出NoSuchElementExcpetion异常。
		deque.remove();
		deque.removeFirst();
		deque.removeLast();
		//删除元素,如果列表为空，这些方法将返回null值
		deque.pollFirst();
		deque.pollLast();
	}
	
	
	
	

}
